package com.cyk.gateway;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.cyk.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebSession;
import reactor.core.publisher.Mono;

// @Order(-1)
@Slf4j
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //1.获取请求和响应
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2.验证是否是登录请求
        if(request.getURI().getPath().contains("/login")) {
            //登录请求直接放行通过
            return chain.filter(exchange);
        }

        //3.用户授权认证
        //1) 获取 token
        String token = request.getHeaders().getFirst("token");
        if(!StringUtils.hasLength(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED); //code: 401
            return response.setComplete();
        }
        //2) 获取用户相关信息
        try {
            DecodedJWT tokenInfo = JwtUtils.getTokenInfo(token);
            log.info("用户 {} 上线, id: {}", tokenInfo.getClaim("username"),
                    tokenInfo.getClaim("userId"));
        } catch (Exception e) {
            log.error("Jwt 解码时引发异常");
            e.printStackTrace();
        }

        //4.放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
